<?php

	namespace Aspic\Database\Mysql;

	use Aspic as A;

	/**
	 * 
	 * @author Mallory Dessaintes
	 */
	class Database extends A\Database\AbstractDatabase {
		protected $_connString = 'mysql:dbname={dbName};host={host}';

		public function __construct($host, $dbName, $username, $password) {
			parent::__construct();
			
			$dbInfos = array(
				'host' => $host, 
				'dbName' => $dbName, 
				'username' => $username, 
				'password' => $password, 
			);

			$this->initPdo($dbInfos);
		}
        
        protected function initPdo(array $dbInfos) {
            $pdoReflection = new \ReflectionClass('PDO');
            
            $this->_dbInfos = $dbInfos;

			$connectionString = A\UString::fromArgsArray($this->_connString, $dbInfos);

			$pdoArgs = array(
				$connectionString,
				A\Util::getIfSet($dbInfos['username']),
				A\Util::getIfSet($dbInfos['password']),
			);

			$this->_pdo = $pdoReflection->newInstanceArgs($pdoArgs);
        }

		public function fetchTablesNames() {
			$sql = 'SELECT table_name FROM information_schema.tables WHERE 
				table_schema NOT IN (\'information_schema\', \'mysql\') AND
				table_schema = "'.$this->_dbInfos['dbName'].'"';

			$raw = $this->getResults($sql);
			$names = array();

			foreach ($raw as $row) {
				$names[] = $row->table_name;
			}

			return $names;
		}
		
		/**
		 * Return the columns of the table from a SQL request to DB
		 */
		public function fetchTableColumns($tableName) {
			$sql = 'SHOW FULL COLUMNS FROM  `'.$tableName.'`';
			$cols = $this->getResults($sql);
			
			$res = array();
			
			foreach ($cols as $col) {
				$res[] = array(
					'name' => $col->Field,
					'type' => $col->Type,
					'null' => $col->Null,
					'default' => $col->Default,
					'key' => $col->Key,
					'extra' => $col->Extra,
					'comment' => $col->Comment,
				);
			}
			
			return $res;
		}
		
		public function fetchForeignsKeys() {
			$sql = '
				SELECT 
					TABLE_NAME as fromTable, 
					COLUMN_NAME as fromColumn, 
					REFERENCED_TABLE_NAME as toTable, 
					REFERENCED_COLUMN_NAME as toColumn 
				FROM 
					information_schema.KEY_COLUMN_USAGE 
				WHERE 
					REFERENCED_TABLE_NAME IS NOT NULL AND
					CONSTRAINT_SCHEMA = '.$this->quote($this->_dbInfos['dbName']).'
			';
			
			$res = $this->getResults($sql);
			
			return $res;
		}

	}

?>
